package com.douwong.student.fragment;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;

import com.douwong.student.R;
import com.douwong.student.activity.ShowClassExamActivity;
import com.douwong.student.adapter.ClassExamAdapter;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.base.BaseFragment;
import com.douwong.student.contant.CommonConfig;
import com.douwong.student.interfaces.DetailNotify;
import com.douwong.student.interfaces.WorkResultNotify;
import com.douwong.student.model.ClassExam;
import com.douwong.student.model.RequestAction;
import com.douwong.student.popuwindow.UpLoadPopuWindow;
import com.douwong.student.task.ClassExamDetailTask;
import com.douwong.student.task.ClassExamListTask;
import com.douwong.student.utils.LogUtils;
import com.douwong.student.utils.ToastUtils;
import com.douwong.student.utils.UIUtils;
import com.douwong.student.view.PullToRefreshListView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @autor yichao
 * @time 2017/5/914:06
 * @des 课堂测验记录
 */
@SuppressLint("ValidFragment")
public class ClassTestFragment extends BaseFragment {
    private List<ClassExam> listData;
    private UpLoadPopuWindow popu;
    private PullToRefreshListView  answer_listview;
    private ImageView statue_img;
    private ClassExamAdapter mAdapter;
    private static final String MTAG = "ClassTestFragment";
    private BaseApplication mBaseApplication;
    private int currentPageIndex;
    private boolean isRefreshing = false;
    private String startTime,endTime,subjectId;
    private Context mContext;

    @Override
    public void onAttach(Context context) {
        mContext = context;
        super.onAttach(context);
        mBaseApplication = (BaseApplication) context.getApplicationContext();
        
    }



    @Override
    protected View getRootView(LayoutInflater inflater, ViewGroup container) {
        View ClassTestView=     UIUtils.inflate(R.layout.class_test_fragment);
        answer_listview = (PullToRefreshListView) ClassTestView.findViewById(R.id.answer_listview);
        statue_img = (ImageView) ClassTestView.findViewById(R.id.statue_img);
        return ClassTestView;
    }


    @Override
    protected void initEvent() {
        super.initEvent();
        answer_listview.setOnILoadMoreListener(new PullToRefreshListView.OnILoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (isRefreshing) {
                    return;
                }
                ++currentPageIndex;
                updateExamData(RequestAction.LOADMROE, currentPageIndex,false);
                isRefreshing = true;
            }
        });
        answer_listview.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {

            @Override
            public void onRefresh() {
                updateExamData(RequestAction.REFRESH, 1,false);
            }
        });
        answer_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                //点击条目
                ClassExamDetailTask task = new ClassExamDetailTask();
                task.setDetailListener(new DetailNotify() {
                    @Override
                    public void notify(int stateCode, String content) {
                        if (stateCode == ClassExamDetailTask.REQUEST_OK) {
                            ShowClassExamActivity.startActivity(mContext,content,listData.get(position - 1).getExResult(),listData.get(position - 1).getExYesNo());

                        }
                    }
                });
                task.execute(listData.get(position - 1).getExamineId() + "");
            }
        });
    }
    @Override
    protected void initData() {
        super.initData();
        mContext.registerReceiver(mReceiver,mFilter);
        listData = new ArrayList<ClassExam>();
        popu=new UpLoadPopuWindow(mContext);
        mAdapter = new ClassExamAdapter(mContext, listData);
        answer_listview.setAdapter(mAdapter);
        updateExamData(RequestAction.INIT, 1,false);

    }

    IntentFilter mFilter=new IntentFilter(){
        {addAction(CommonConfig.TEST_SEARCH);}
    };

    BroadcastReceiver mReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case CommonConfig.TEST_SEARCH :
                    startTime = intent.getStringExtra("start_time");
                  endTime=intent.getStringExtra("end_time");
               subjectId=intent.getStringExtra("subjectId");

                    updateExamData(RequestAction.REFRESH, 1,true);
                    statue_img.setVisibility(View.INVISIBLE);
                    listData.clear();
                    mAdapter.notifyDataSetChanged();
                    popu.showAtLocation(getView(), Gravity.CENTER,0,0);
                    popu.setText("加载中...");
                    break;
            }


        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mReceiver!=null){
        mContext.unregisterReceiver(mReceiver);
            mReceiver=null;
        }
        if (popu!=null && popu.isShowing()){
            popu.dismiss();
        }
    }

    /**
     * 更新数据
     * @param action
     * @param pageIndex
     * @param isSearch
     */
    protected void updateExamData(final RequestAction action, final int pageIndex,boolean isSearch) {
        LogUtils.i(MTAG,"当前访问的RequestAction ： "+action+"____当前访问pageIndex ：  "+ pageIndex);
        ClassExamListTask task = new ClassExamListTask(action, mBaseApplication,isSearch);
        task.setWorkStautsListener(new WorkResultNotify<ClassExam>() {

            @Override
            public void notify(int stateCode, List<ClassExam> arryResult) {

                LogUtils.i(MTAG,"这时的stateCode  :  "+stateCode+"RequestAction : "+action+"_____________arryResult : "+((arryResult==null)?0:arryResult.size())+"_____pageIndex  : "+ pageIndex);

                if (ClassExamListTask.NO_DATA == stateCode) {

                    // 加载更多时，出现异常或者没有多余数据，要将currentPageIndex回到加载数据前的一页
                    if (currentPageIndex > 1 && RequestAction.LOADMROE == action) {
                        --currentPageIndex;
                        ToastUtils.makeText(BaseApplication.mContext,"没有更多数据了");
                    }
                    if (arryResult == null && action != RequestAction.LOADMROE) {
                        statue_img.setVisibility(View.VISIBLE);
                        statue_img.setImageResource(R.mipmap.no_record);
                        listData.clear();
                    }

                } else if (ClassExamListTask.REQUESTOK == stateCode) {
                    // 其他访问类型均需要清空当前数据，重新显示，加载更多是在原有的数据上增加
                    if (RequestAction.LOADMROE != action) {
                        listData.clear();
                    }

                    if (arryResult != null && arryResult.size() > 0) {
                        statue_img.setVisibility(View.INVISIBLE);
                        listData.addAll(arryResult);
                        Collections.sort(listData);
                    } else {
                        statue_img.setVisibility(View.VISIBLE);
                        statue_img.setImageResource(R.mipmap.no_record);
                    }

                } else if (ClassExamListTask.NO_NETWOK == stateCode) {
                    if (pageIndex==1){
                        statue_img.setVisibility(View.VISIBLE);
                        statue_img.setImageResource(R.mipmap.no_wifi);
                        listData.clear();
                        mAdapter.notifyDataSetChanged();
                    }
                    ToastUtils.makeText(BaseApplication.mContext,"请检查网络");

                }
                if(popu.isShowing()){
                    popu.dismiss();
                }
                isRefreshing = false;
                answer_listview.onRefreshComplete();
                answer_listview.completeLoadMore();
                mAdapter.notifyDataSetChanged();
            }
        });
        if (BaseApplication.sUserBean!= null) {
            task.executeOnExecutor((ExecutorService) Executors.newCachedThreadPool(),String.valueOf(pageIndex), startTime, endTime,subjectId);
        } else {
            statue_img.setVisibility(View.VISIBLE);
            statue_img.setImageResource(R.mipmap.no_record);
            isRefreshing = false;
            answer_listview.completeLoadMore();
            answer_listview.onRefreshComplete();
        }
    }

}
